<!-- src/view/PasswordReset.vue -->
<template>
  <div class="password-reset-container">
    <div class="password-reset-form">
      <h2>重置密码</h2>

      <!-- 步骤指示器 -->
      <el-steps :active="step" finish-status="success" simple>
        <el-step title="填写邮箱" />
        <el-step title="验证邮箱" />
        <el-step title="重置密码" />
      </el-steps>

      <!-- 步骤1: 填写邮箱 -->
      <div v-if="step === 1" class="step-content">
        <el-form :model="emailForm" :rules="emailRules" ref="emailFormRef">
          <el-form-item prop="email">
            <el-input
                v-model="emailForm.email"
                placeholder="请输入注册邮箱"
                prefix-icon="Message"
            />
          </el-form-item>
          <el-form-item>
            <el-button
                type="primary"
                @click="sendVerificationCode"
                :loading="loading"
                style="width: 100%"
            >
              发送验证码
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤2: 验证邮箱 -->
      <div v-else-if="step === 2" class="step-content">
        <p>验证码已发送至: {{ emailForm.email }}</p>
        <el-form :model="verifyForm" :rules="verifyRules" ref="verifyFormRef">
          <el-form-item prop="code">
            <el-input
                v-model="verifyForm.code"
                placeholder="请输入验证码"
                prefix-icon="Key"
            />
          </el-form-item>
          <div class="countdown">
            验证码有效期: {{ countdown }}秒
          </div>
          <el-form-item>
            <el-button
                type="primary"
                @click="verifyCode"
                :loading="loading"
                style="width: 100%"
            >
              验证
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click="resendCode" :disabled="countdown > 0">
              重新发送验证码 {{ countdown > 0 ? `(${countdown}s)` : '' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤3: 重置密码 -->
      <div v-else-if="step === 3" class="step-content">
        <el-form :model="resetForm" :rules="resetRules" ref="resetFormRef">
          <el-form-item prop="newPassword">
            <el-input
                v-model="resetForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                prefix-icon="Lock"
                show-password
            />
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input
                v-model="resetForm.confirmPassword"
                type="password"
                placeholder="请确认新密码"
                prefix-icon="Lock"
                show-password
            />
          </el-form-item>
          <el-form-item>
            <el-button
                type="primary"
                @click="resetPassword"
                :loading="loading"
                style="width: 100%"
            >
              重置密码
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 返回登录 -->
      <div class="back-to-login">
        <el-button type="text" @click="backToLogin">
          ← 返回登录
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import passwordResetApi from '../api/passwordResetApi.js'

const router = useRouter()

// 步骤控制
const step = ref(1)

// 表单引用
const emailFormRef = ref()
const verifyFormRef = ref()
const resetFormRef = ref()

// 表单数据
const emailForm = reactive({
  email: ''
})

const verifyForm = reactive({
  code: ''
})

const resetForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

// 验证规则
const emailRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const verifyRules = {
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

const resetRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 状态控制
const loading = ref(false)
const countdown = ref(0)
let countdownTimer = null

// 发送验证码
const sendVerificationCode = async () => {
  if (!emailFormRef.value) return

  await emailFormRef.value.validate(async (valid) => {
    if (!valid) return

    loading.value = true
    try {
      const res = await passwordResetApi.sendCode({ email: emailForm.email })
      if (res && res.code === 200) {
        ElMessage.success('验证码已发送，请查收邮箱')
        step.value = 2
        startCountdown()
      } else {
        ElMessage.error(res?.msg || '发送验证码失败')
      }
    } catch (err) {
      ElMessage.error('发送验证码失败: ' + (err.message || '请检查网络连接'))
    } finally {
      loading.value = false
    }
  })
}

// 验证验证码
const verifyCode = async () => {
  if (!verifyFormRef.value) return

  await verifyFormRef.value.validate(async (valid) => {
    if (!valid) return

    loading.value = true
    try {
      const res = await passwordResetApi.verifyCode({
        email: emailForm.email,
        code: verifyForm.code
      })

      if (res && res.code === 200) {
        ElMessage.success('验证码验证成功')
        step.value = 3
        clearCountdown()
      } else {
        ElMessage.error(res?.msg || '验证码验证失败')
      }
    } catch (err) {
      ElMessage.error('验证码验证失败: ' + (err.message || '请检查网络连接'))
    } finally {
      loading.value = false
    }
  })
}

// 重置密码
const resetPassword = async () => {
  if (!resetFormRef.value) return

  await resetFormRef.value.validate(async (valid) => {
    if (!valid) return

    loading.value = true
    try {
      const res = await passwordResetApi.reset({
        email: emailForm.email,
        newPassword: resetForm.newPassword
      })

      if (res && res.code === 200) {
        ElMessage.success('密码重置成功，请使用新密码登录')
        // 清除可能存在的旧登录状态
        localStorage.removeItem("token")
        localStorage.removeItem("userInfo")
        setTimeout(() => {
          router.push('/login')
        }, 1500)
      } else {
        ElMessage.error(res?.msg || '密码重置失败')
      }
    } catch (err) {
      ElMessage.error('密码重置失败: ' + (err.message || '请检查网络连接'))
    } finally {
      loading.value = false
    }
  })
}

// 重新发送验证码
const resendCode = async () => {
  if (countdown.value > 0) return

  loading.value = true
  try {
    const res = await passwordResetApi.sendCode({ email: emailForm.email })
    if (res && res.code === 200) {
      ElMessage.success('验证码已重新发送')
      startCountdown()
    } else {
      ElMessage.error(res?.msg || '发送验证码失败')
    }
  } catch (err) {
    ElMessage.error('发送验证码失败: ' + (err.message || '请检查网络连接'))
  } finally {
    loading.value = false
  }
}

// 倒计时功能
const startCountdown = () => {
  countdown.value = 60
  countdownTimer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearCountdown()
    }
  }, 1000)
}

const clearCountdown = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
}

// 返回登录
const backToLogin = () => {
  router.push('/login')
}

// 组件销毁时清理定时器
onUnmounted(() => {
  clearCountdown()
})
</script>

<style scoped>
.password-reset-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.password-reset-form {
  width: 400px;
  padding: 40px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
}

.password-reset-form h2 {
  margin-bottom: 30px;
  color: #333;
}

.step-content {
  margin: 30px 0;
}

.countdown {
  margin: 10px 0;
  color: #999;
  font-size: 14px;
}

.back-to-login {
  text-align: center;
}
</style>
